from django.http import HttpResponse
from django.shortcuts import render
from DjangoWeb import models
from DjangoWeb.Validate import validate
from django.contrib import messages
from DjangoWeb.Myforms import myforms
from django.core.exceptions import ObjectDoesNotExist
import time

# user_list = []

'''
# Create your views here.
def index(request):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 将数据保存到数据库
        models.User.objects.create(user=username, pwd=password)

    # 从数据库中读取所有数据，注意缩进
    user_list = models.User.objects.all()
    return render(request, 'index.html', {'data': user_list})
'''

account = 'zwc233'
now_account = ''


def index(request):
    return render(request, 'index.html')


def lesson_choose(request):
    if time_judge():
        # chose lesson
        course_id = request.POST.get("Choose")
        if course_id is not None and not now_account == '':
            COURSE = models.Course.objects.get(Course_id=course_id)
            try:
                models.TakeCourse.objects.get(account=now_account, Course_id=COURSE)
                messages.success(request, "您已经选择过此课程")
            except ObjectDoesNotExist:
                temp = models.NowCapacity.objects.get(Course_id=COURSE)
                if temp.now_capacity > 0:
                    temp.now_capacity -= 1
                    temp.save()
                    models.TakeCourse(Course_id=COURSE, account=now_account).save()
                    messages.success(request, "课程已选择")
                else:
                    messages.success(request, "余量不足")
    else:
        messages.success(request, "不在选课时间内")

    # search lesson
    form = myforms.LessonChooseForm(request.POST)
    if form.is_valid():
        ID = form.cleaned_data.get('ID')
        lesson_name = form.cleaned_data.get('lesson_name')
        teacher_name = form.cleaned_data.get('teacher_name')
        if ID == 0 or ID is None:
            Answer = models.Course.objects.filter(name__contains=lesson_name, teacher_name__contains=teacher_name)
        else:
            Answer = models.Course.objects.filter(Course_id=ID)
        return render(request, '课程选择.html', {'data': generate_course(Answer)})
    else:
        messages.success(request, "请输入数字ID")
        return render(request, '课程选择.html')


def prelesson_choose(request):
    # chose prelesson
    course_id = request.POST.get("Choose")
    if course_id is not None and not now_account == '':
        COURSE = models.Course.objects.get(Course_id=course_id)
        try:
            models.TrainingProgram.objects.get(account=now_account, Course=COURSE)
            messages.success(request, "您已经选择过此课程")
        except ObjectDoesNotExist:
            models.TrainingProgram(Course=COURSE, account=now_account).save()
            messages.success(request, "课程已选择")

    # delete prelesson
    delete_id = request.POST.get("UnChoose")
    if delete_id is not None and not now_account == '':
        COURSE = models.Course.objects.get(Course_id=delete_id)
        try:
            models.TrainingProgram.objects.get(Course=COURSE, account=now_account).delete()
            messages.success(request, "删除课程成功")
        except ObjectDoesNotExist:
            messages.success(request, "您培养方案中没有该课程")

    # generate pre_lessons
    pre_lessons = []
    zip_pre_lessons = []
    try:
        if not now_account == '':
            for i in models.TrainingProgram.objects.filter(account=now_account):
                pre_lessons.append(i.Course)
            if pre_lessons:
                zip_pre_lessons = generate_course(pre_lessons)
    except ObjectDoesNotExist:
        pass

    # search lesson
    form = myforms.LessonChooseForm(request.POST)
    if form.is_valid():
        ID = form.cleaned_data.get('ID')
        lesson_name = form.cleaned_data.get('lesson_name')
        teacher_name = form.cleaned_data.get('teacher_name')
        if ID == 0 or ID is None:
            Answer = models.Course.objects.filter(name__contains=lesson_name, teacher_name__contains=teacher_name)
        else:
            Answer = models.Course.objects.filter(Course_id=ID)
        return render(request, '培养方案定制.html', {'data': generate_course(Answer), 'show_lessons': zip_pre_lessons})
    else:
        messages.success(request, "请输入数字ID")
        return render(request, '培养方案定制.html')


def change_pwd(request):
    return render(request, '修改密码.html')


def set_time(request):
    form = myforms.SetTimeForm(request.POST)
    if form.is_valid():
        t1m = form.cleaned_data.get('t1m')
        t1d = form.cleaned_data.get('t1d')
        t2m = form.cleaned_data.get('t2m')
        t2d = form.cleaned_data.get('t2d')
        strT1 = '2021-' + str(t1m) + '-' + str(t1d)
        strT2 = '2021-' + str(t2m) + '-' + str(t2d)
        if not compare_time(strT2, strT1):
            messages.success(request, "结束时间在开始时间之前！")
        else:
            if request.POST.get('first') is not None:
                second = models.SelectChooseClassTime.objects.get(id=2)
                if not compare_time(str(second.start_date.date()), strT2):
                    messages.success(request, "二轮开始时间在一轮结束时间之前！")
                else:
                    temp = models.SelectChooseClassTime.objects.get(id=1)
                    temp.start_date = strT1
                    temp.end_date = strT2
                    temp.save()
            elif request.POST.get('second') is not None:
                first = models.SelectChooseClassTime.objects.get(id=1)
                if not compare_time(strT1, str(first.end_date.date())):
                    messages.success(request, "二轮开始时间在一轮结束时间之前！")
                else:
                    temp = models.SelectChooseClassTime.objects.get(id=2)
                    temp.start_date = strT1
                    temp.end_date = strT2
                    temp.save()
            else:
                pass
    else:
        pass
    show = models.SelectChooseClassTime.objects.filter()
    return render(request, '选课时间设定.html', {'data': show})


def login(request):
    return render(request, '登录.html')


def student_twice_choose(request):
    global now_account
    c_bit = 1  # 1 is Course and 0 is student
    now_s_id = request.POST.get("Choose_s")
    if now_s_id:
        now_account = models.users.objects.get(account=now_s_id)

    course_id = request.POST.get("Choose")
    if course_id is not None and not now_account == '':
        User_ID = account
        COURSE = models.Course.objects.get(Course_id=course_id)
        ACCOUNT = models.users.objects.get(account=now_account.account)
        try:
            models.TakeCourse.objects.get(account=ACCOUNT, Course_id=COURSE)
            messages.success(request, "该生已经选择过此课程")
        except ObjectDoesNotExist:
            temp = models.NowCapacity.objects.get(Course_id=COURSE)
            if temp.now_capacity > 0:
                temp.now_capacity -= 1
                temp.save()
                models.TakeCourse(Course_id=COURSE, account=ACCOUNT).save()
                messages.success(request, "该生课程已选择")
            else:
                messages.success(request, "余量不足")

    if request.POST.get("course"):
        form = myforms.LessonChooseForm(request.POST)
        if form.is_valid():
            ID = form.cleaned_data.get('ID')
            lesson_name = form.cleaned_data.get('lesson_name')
            teacher_name = form.cleaned_data.get('teacher_name')
            if ID == 0 or ID is None:
                Answer = models.Course.objects.filter(name__contains=lesson_name, teacher_name__contains=teacher_name)
            else:
                Answer = models.Course.objects.filter(Course_id=ID)
            return render(request, '学生补选.html', {'data': generate_course(Answer), 'c_bit': 1, 'n_s': now_account})
        else:
            messages.success(request, "请输入数字ID")
            return render(request, '学生补选.html')
    elif request.POST.get("student"):
        student_name = request.POST.get("student_name")
        Account = request.POST.get("account")
        college = request.POST.get("college")
        Answer = models.users.objects.filter(name__contains=student_name, account__contains=Account,
                                             college__contains=college, status=3)
        return render(request, '学生补选.html', {'data': Answer, 'c_bit': 0, 'n_s': now_account})

    return render(request, '学生补选.html', {'n_s': now_account})


def lesson_result_student(request):
    ACCOUNT = ''
    if not now_account == '':
        ACCOUNT = models.users.objects.get(account=now_account.account)
    else:
        ACCOUNT = models.users.objects.get(account=account)
    TAKE = models.TakeCourse.objects.filter(account=ACCOUNT)
    Course = []
    for i in TAKE:
        Course.append(i.Course_id)
    data = generate_course(Course)

    delete_course_id = request.POST.get("Choose")
    if time_judge():
        try:
            delete_course = models.Course.objects.get(Course_id=delete_course_id)
            del_rec = models.TakeCourse.objects.get(account=ACCOUNT, Course_id=delete_course)
            del_rec.delete()

            raise_capacity = models.NowCapacity.objects.get(Course_id=delete_course)
            raise_capacity.now_capacity += 1
            raise_capacity.save()

            TAKE = models.TakeCourse.objects.filter(account=ACCOUNT)
            Course = []
            for i in TAKE:
                Course.append(i.Course_id)
            data = generate_course(Course)

            messages.success(request, "退课成功")
        except ObjectDoesNotExist:
            pass
    else:
        messages.success(request, "不在选课时间范围内")
    return render(request, '选课结果-学生.html', {'data': data})


def lesson_result_teacher(request):
    Account = 'tc567'
    Teacher = models.users.objects.get(account=Account)
    Course = models.Course.objects.filter(teacher_name=Teacher.name)
    Students = []
    if request.POST.get("Choose"):
        Course_id = request.POST.get("Choose")
        choose_course = models.Course.objects.get(Course_id=Course_id)
        for i in models.TakeCourse.objects.filter(Course_id=choose_course):
            Students.append(i.account)
    return render(request, '选课结果-教师.html', {'data': generate_course(Course), 'students': Students})


def pro(request):
    return render(request, '选课时间设定.html')


def compare_time(time1, time2):
    s_time = time.mktime(time.strptime(time1, '%Y-%m-%d'))
    e_time = time.mktime(time.strptime(time2, '%Y-%m-%d'))
    if int(s_time) - int(e_time) > 0:
        return True
    else:
        return False


def generate_course(course_all):
    Capacity = []
    Arrange = []
    Address = []
    Core = []
    try:
        for i in course_all:
            temp_a = models.ArrangeResult.objects.get(Course=i.Course_id)
            Arrange.append(temp_a)
            Address.append(temp_a.ClassRoom)
            Capacity.append(models.NowCapacity.objects.get(Course_id=i.Course_id))
            Core.append(models.CoreCourse.objects.get(Course=i.Course_id))
    except ObjectDoesNotExist:
        pass
    return zip(course_all, Capacity, Arrange, Address, Core)


def time_judge():
    strNow = time.strftime("%Y-%m-%d", time.localtime())
    t11 = str(models.SelectChooseClassTime.objects.get(id=1).start_date.date())
    t12 = str(models.SelectChooseClassTime.objects.get(id=1).end_date.date())
    t21 = str(models.SelectChooseClassTime.objects.get(id=2).start_date.date())
    t22 = str(models.SelectChooseClassTime.objects.get(id=2).end_date.date())

    if (compare_time(strNow, t11) and not compare_time(strNow, t12)) or (
            compare_time(strNow, t21) and not compare_time(strNow, t22)):
        return True
    else:
        return False
